#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <opencv2/opencv.hpp>

#include "kinectfusion/main.h"
using namespace std;
using namespace cv;

#include <QThread>

#include <QImage>

#include <QObject>

// void Mythread::drawImage()
// {
//     // 绘画设备
//     QImage image(500, 500, QImage::Format_ARGB32);
//     emit updataImage(image);
// }
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QString filename("/home/u20/ros/src/markermapper/kinectfusion/img/rgb/0.png");
    QImage *img = new QImage;
    if (!(img->load(filename))) // 加载图像
    {
        // QMessageBox::information(this,
        //                          tr("打开图像失败"),
        //                          tr("打开图像失败!"));
        delete img;
        return;
    }
    QImage q2 = img->scaled(320, 240);
    ui->label->setPixmap(QPixmap::fromImage(q2));
    ui->label->resize(320, 240);

    Mat srcImage = imread("/home/u20/ros/src/markermapper/kinectfusion/img/rgb/0.png");
    int width = srcImage.cols;
    int height = srcImage.rows;
    cvtColor(srcImage, srcImage, COLOR_BGR2RGB);
    QImage disImage = QImage(srcImage.data, width, height,
                             QImage::Format_RGB888);
    scene = new QGraphicsScene[4];
    ui->graphicsView->setScene(&scene[0]);
    ui->graphicsView->show();

    ui->graphicsView_2->setScene(&scene[1]);
    ui->graphicsView_2->show();

    ui->graphicsView_3->setScene(&scene[2]);
    ui->graphicsView_3->show();

    QStringList imagePathList;
    this->pThread = new ImageLoadingThread(imagePathList);
    // thread = new QThread(this);
    // myT->moveToThread(thread);

    // connect(ui->pushButton,&QPushButton::pressed,myT,&Mythread::drawImage);
    // 子线程绘图函数 drawImage（）必须通过 signals-- slots来调用实现
    //  connect(myT,&Mythread::updataImage,this,&MainWindow::getImage);
    connect(pThread, &ImageLoadingThread::image, this, &MainWindow::setImages);
    this->pThread->start(ImageLoadingThread::Direction::Left);
    // connect(this,&MainWindow::destroyed,this,&MainWindow::kill_thread);
}
int MainWindow::setImages(int index, const QImage &img)

{
    scene[index].addPixmap(QPixmap::fromImage(img));
    // m_pFunctionWidget是保存设置得到的图像
    // m_pFunctionWidget->setImage(index, img);
    std::cout << "index " << index << endl;

    // // 下面的if语句段是为了实现左右交替显示图片

    // if (m_pImgLoadingThread->previousDirection() == ImageLoadingThread::Left)

    //     m_pImgLoadingThread->start(ImageLoadingThread::Right);

    // else

    //     m_pImgLoadingThread->start(ImageLoadingThread::Left);
}
void MainWindow::getImage(QImage temp)
{
    QImage image = temp; // 用于接受子线程传回来的图像
    update();            // 更新窗口，间接调用paintEvent绘画
}

void MainWindow::kill_thread()
{
    thread->quit(); // 退出子线程
    thread->wait(); // 处理子线程所占用的资源
    delete thread;  // 由于test_thread没有指定父对象 需要自己处理
}
MainWindow::~MainWindow()
{
    delete ui;
}
